<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :title="$t('uploadPAT')"
    width="40%">
    <el-form ref="form" :model="infoForm" label-width="120px">
      <el-form-item
        :rules="[
          { required: true, message: '请上传文件', trigger: 'change' },
        ]"
        prop="fileList"
        label="选择文件"
      >
        <el-upload
          ref="upload"
          :action="baseApi + '/tdm/Upload/UploadPat'"
          :headers="headers"
          :on-change="uploadChange"
          :on-remove="onRemove"
          :auto-upload="false"
          :http-request="httpRequest"
          :file-list="infoForm.fileList"
          :multiple="true"
          style="display: inline-block"
          accept=".cpe,.csv"
        >
          <el-button
            type="primary"
            icon="el-icon-upload"
          >{{ $t("import") }}</el-button
          >
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button
        icon="el-icon-circle-close"
        @click="handleClose"
      >{{ $t("cancel") }}</el-button>
      <el-button
        v-btnThrottle="doSave"
        type="primary"
        icon="el-icon-receiving"
      >{{ $t("save") }}</el-button>
  </span></el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { doUploadPat } from '@/api/ruleConfig/uploadPat'
export default {
  name: 'UploadPATFile',
  data() {
    return {
      dialogVisible: false,
      infoForm: {
        fileList: []
      },
      headers: {
        Token: getToken()
      },
      globalfd: null
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  methods: {
    handleOpen() {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    doSave() {
      const moreThan10M = this.$refs.upload.uploadFiles.filter(file => file.size / 1024 / 1024 > 10)
      if (moreThan10M.length) {
        const listVNode = moreThan10M.map(item => {
          return (
            <p>{item.name.replace(/.cpe$|.csv$/g, '')} {this.$t('fileSizeLimit')} 10MB!</p>
          )
        })
        this.$notify({
          message: this.$createElement('div', { style: 'color: teal' }, listVNode),
          type: 'error',
          duration: 0
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.globalfd = new FormData()
            this.$refs.upload.submit()
            doUploadPat(this.globalfd).then(res => {
              if (res.code === 1) {
                this.$betterTips(res, this.handleClose, this.handleUpdate)
              } else {
                this.$betterTips(res)
              }
            })
          } else {
            return false
          }
        })
      }
    },
    httpRequest({ file }) {
      this.globalfd.append('file', file, file.name)
    },
    handleClose() {
      Object.assign(this.$data, this.$options.data.call(this))
    },
    handleUpdate() {
      this.$emit('initList')
    },
    uploadChange(file, fileList) {
      const existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
      if (existFile) {
        fileList.pop()
      }
      this.infoForm.fileList = fileList
      this.$refs['form'].validateField('fileList')
    },
    onRemove(file, fileList) {
      this.infoForm.fileList = fileList
    }
    // uploadSuccess(response, file, fileList) {
    //   if (response.code !== 1) {
    //     const h = this.$createElement
    //     const listVNode = response.data.map((item) => {
    //       return (
    //         <p>
    //           <span>{item.index ? `第{${item.index}}行` : ''}</span>
    //           <span>{this.$t(item.msgCode)}</span>
    //         </p>
    //       )
    //     })
    //     this.$notify({
    //       message: h('div', { style: 'color: teal' }, listVNode),
    //       type: 'error',
    //       duration: 0
    //     })
    //   } else {
    //     this.$betterTips(response, this.$refs.upload.clearFiles, this.handleClose)
    //   }
    // },
    // importFail(err, file) {
    //   const errMessage = JSON.parse(err.toString().replace('Error: ', ''))
    //   this.$notify({
    //     message: this.$t(String(errMessage.code)),
    //     type: 'error',
    //     duration: 0
    //   })
    // }
  }
}
</script>
